package com.myproject.sbp.apigateway.zuul.filter;

import com.alibaba.fastjson.JSONObject;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.support.RateLimitExceededException;
import com.myproject.sbp.base.common.RespCommon;
import com.myproject.sbp.base.common.RespEnum;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * zuul异常统一处理
 * @author ywh
 */
@Slf4j
@Component
public class ExceptionFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            Object e = ctx.get("throwable");
            if (e != null && e instanceof ZuulException) {
                RespCommon respCommon = null;
                ZuulException zuulException = (ZuulException) e;
                log.error("调用服务异常", zuulException);
                if(null != zuulException.getCause() && zuulException.getCause() instanceof RateLimitExceededException) {
                    RateLimitExceededException rateLimitExceededException = (RateLimitExceededException) zuulException.getCause();
                    respCommon = RespCommon.result(RespEnum.ZUUL_EXCEPTION.getCode(), rateLimitExceededException.getMessage());
                }else{
                    respCommon = RespCommon.result(RespEnum.ZUUL_EXCEPTION);
                }
                // 删除该异常信息,不然在下一个过滤器中还会被执行处理
                ctx.remove("throwable");
                ctx.setResponseBody(JSONObject.toJSONString(respCommon));
                ctx.getResponse().setContentType("application/json;charset=UTF-8");
                // 根据具体的业务逻辑来处理
                ctx.setResponseStatusCode(500);
            }
        } catch (Exception ex) {
            log.error("异常处理异常！！！！");
        }
        return null;
    }
}
